package com.vendar.quicknote;

import com.vendar.email.EMailHelper;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendEMailActivity extends Activity implements OnClickListener {
	private EditText mRecipient = null;
	private EditText mSubject = null;
	private EditText mBody = null;
	private Button mSend = null;
	private EMailHelper mEMailHelper = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.send_email);
		Setup();
	}
	
	private void Setup(){
		mRecipient = (EditText)findViewById(R.id.recipient_editor);
		mSubject = (EditText)findViewById(R.id.subject_editor);
		mBody = (EditText)findViewById(R.id.body_editor);
		mSend = (Button)findViewById(R.id.send_btn);
		
		mSend.setOnClickListener(this);
		
		if( !ReadIntentData(getIntent().getExtras()) ){
			System.err.println("read email account failed!");
		}
	}
	
	private boolean ReadIntentData(Bundle extras){
		if( extras == null ) return false;
		
		String username = extras.getString("username");
		String password = extras.getString("password");
		String smtpHost = extras.getString("smtp_host");
		String smtpPort = extras.getString("smtp_port");
		mBody.setText(extras.getString("content"));
		
		if( username!=null && password!=null
		&& smtpHost!=null && smtpPort!=null ){
			mEMailHelper = new EMailHelper(username, password);
			mEMailHelper.SetupServer(smtpHost, smtpPort);
			return true;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		if( v==mSend ){
			//information validity check
			String recipient = mRecipient.getText().toString();
			if( recipient == null || recipient.length()<0 ){
				Toast.makeText(this, R.string.recipient_cannot_be_null, 500).show();
				return ;
			}
			String subject = mSubject.getText().toString();
			if( subject == null || subject.length()<0 ){
				Toast.makeText(this, R.string.subject_cannot_be_null, 500).show();
				return ;
			}
			String body = mBody.getText().toString();
			if( body == null || body.length()<0 ){
				Toast.makeText(this, R.string.body_cannot_be_null, 500).show();
				return ;
			}
			
			//send email, we don't support attachments yet now!
			if( mEMailHelper.Send(new String[]{recipient}, subject, body, null) ){
				Toast.makeText(this, R.string.send_email_succeed, 500);
				//TODO check up modified note,save it.
				this.finish();
			}else{
				Toast.makeText(this, R.string.send_email_failed, 500);
				return ;
			}
		}
	}
}
